package com.gq.dungsihesman;

import java.util.LinkedHashMap;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.gq.tab.MyTab;
import com.gq.tab.Tab1;
import com.gq.tab.Tab2;
import com.gq.utils.NetworkState;
import com.nullwire.trace.ExceptionHandler;
import com.rtst.widget.actionbar.ActionBarActivity;
import com.rtst.widget.tab.ITabHost;
import com.rtst.widget.tab.SwipeyTabs;
import com.rtst.widget.tab.SwipeyTabsAdapter;
import com.rtst.widget.tab.TabFragment;

public class MainActivity extends ActionBarActivity implements ITabHost {
	/** Called when the activity is first created. */
	private static final String TAG = "MainActivity";
	private volatile static MainActivity instance;
	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	public static final int EXIT_RESULT = 0x1;
	public static final String PEFERENCE_FILE = "pref_manaportal";
	public static final String CLIENT_VERSION = "MP_ANDROID_1.0.0";
	private DisplayMetrics disMetric = new DisplayMetrics();
    public static final String HTTP_EXCEPTION_HANDLE_URL = "http://a.p.mana.vn/e/handle";
    private LinkedHashMap<Integer, Fragment> tabPages = new LinkedHashMap<Integer, Fragment>();
    private int mLastTabId = 0;


	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (instance == null) instance = this;
		super.onCreate(savedInstanceState);
		ExceptionHandler.register(this, HTTP_EXCEPTION_HANDLE_URL);			// http://code.google.com/p/android-remote-stacktrace/
		setContentView(R.layout.activity_swipeytab);
		new NetworkState(MainActivity.this).check();
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager());
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
		mTabs.setVisibility(View.GONE);
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setCurrentItem(0);
		Toast.makeText(this, "Hãy click vào quảng cáo để ủng hộ tác giả bạn nhé ^_^", Toast.LENGTH_LONG).show();
	}
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.home, menu);

		// Calling super after populating the menu is necessary here to ensure
		// that the
		// action bar helpers have a chance to handle this event.
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				//Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show();
				break;
				
			case R.id.menu_info:
				startActivity(new Intent(this, MoreAppActivity.class));
				break;
			
			case R.id.menu_sort:
				mCurTabFragment = ((MyTab) tabPages.get(Integer.valueOf(mLastTabId))).getCurTabFragment();
				if(mCurTabFragment instanceof ISortInterface) {
					((ISortInterface)mCurTabFragment).reverse();
				}
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
			SwipeyTabsAdapter, OnTabChangeListener {

		private final String[] TITLES = { 
				"BỘ 1",
		};

		private final Context mContext;
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
			this.mContext = context;
		}

		@Override
		public Fragment getItem(int position) {
			Fragment fg = null;
			switch (position) {
			case 0:
				fg = new Tab1();
				break;
			case 1:
				fg = new Tab2();
				break;
//			default:
//				fg = new CategoryTab(CategoryScr.TYPE_HOME);
//				break;
			}
			tabPages.put(position, fg);
			return fg;
		}

		@Override
		public int getCount() {
			return TITLES.length;
		}

		public ViewGroup getTab(final int position, SwipeyTabs root) {
			ViewGroup layout = (ViewGroup) LayoutInflater.from(mContext)
					.inflate(R.layout.swipey_tab_indicator, root, false);

			TextView view = (TextView) layout.findViewById(R.id.swipey_tab);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			return layout;
		}

		@Override
		public void onTabChanged(String tabId) {
			Log.i(TAG, "onTabChanged " + tabId);
			try {
				mCurTabFragment = ((MyTab) tabPages.get(Integer.valueOf(tabId))).getCurTabFragment();
				mCurTabFragment.refresh();
			} catch(Exception e) {
				mCurTabFragment = null;
			}
			mLastTabId = Integer.parseInt(tabId);
		}
	}
	

	@Override
	public int getContainerViewId() {
		return getTabContainerViewId(mViewPager.getCurrentItem());
	}

	@Override
	public int getTabContainerViewId(int id) {
		int containerId = 0;
		switch (id) {
		case 0:
			containerId = R.id.tab_category_container;
			break;
		}
		return containerId;
	}

	TabFragment mCurTabFragment;
	@Override
	public void setCurTabFragment(TabFragment fragment) {
		if(fragment == null) return;
		mCurTabFragment = fragment;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
				&& keyCode == KeyEvent.KEYCODE_BACK
				&& event.getRepeatCount() == 0) {
			// Take care of calling this method on earlier versions of
			// the platform where it doesn't exist.
			onBackPressed();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onBackPressed() {
	    // This will be called either automatically for you on 2.0
	    // or later, or by the code above on earlier versions of the
	    // platform.
		mCurTabFragment.onBack();
	    return;
	}
	
	public static MainActivity getInstance() {
		if (instance == null) {
			synchronized (MainActivity.class) {
				if (instance == null) {
					instance = new MainActivity();
				}
			}
		}
		return instance;
	}
	
	public String getCarrierName() {
		TelephonyManager manager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
		String carrierName = manager.getNetworkOperatorName();
		return carrierName;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public String getIMEI() {
		TelephonyManager telephoneMgr = (TelephonyManager) getSystemService(getBaseContext().TELEPHONY_SERVICE);
		return telephoneMgr.getDeviceId();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	public int[] getDisplayDimension() {
		getWindowManager().getDefaultDisplay().getMetrics(disMetric);
		int[] dimension = new int[] { disMetric.widthPixels, disMetric.heightPixels };
		return dimension;
	}
	
	public String getDisplayDimensionStr() {
		int[] dimension = getDisplayDimension();
		return String.format("%dx%d", dimension[0], dimension[1]);
	}
}